// 1.导入http模块
const http = require("http");
//2.导入fs模块
const fs = require("fs");
//3.导入path木块
const path = require("path");
/* MIME常见类型: [type]（主类型）/[subType](子类型)
  html: 'text/html',
  css: 'text/css',
  js: 'text/javascript',
  png: 'image/png',
  jpg: 'image/jpg',
  gif: 'image/git',
  mp4 : 'video/mp4',
  mp3: 'video/mp3',
  json: 'application/json', 
  未知资源类型(unknown)：application/octet-stream
  */

//声明一个变量
let mimes = {
  html: "text/html",
  css: "text/css",
  js: "text/javascript",
  png: "image/png",
  jpg: "image/jpg",
  gif: "image/git",
  mp4: "video/mp4",
  mp3: "video/mp3",
  json: "application/json",
  unknown:'application/octet-stream'
};

const server = http.createServer((request, response) => {
  let { pathname } = new URL(request.url, "http://192.168.101.159");
  let root = path.dirname(__dirname) + "/resource";
  //拼接文件路径
  let filePath = root + pathname;
  //读取文件  fs异步API
  fs.readFile(filePath, (err, data) => {
    if (err) {
      // 设置字符集
      response.setHeader("content-Type", "text/html;charset=utf-8");
      // 判断错误的代号
      switch (err.code) {
        case 'ENOENT':
          response.statusCode = 404;
          response.end('<h1>404 Not Found</h1>');
          break;
        case 'EPERM':
          response.statusCode = 403;
          response.end('<h1>403 Forbidden</h1>');
          break;
        default:
          response.statusCode = 500;
          response.end('<h1>Internal Server Error</h1>');
          break;
      }
      return;
    }
    //获取文件的后缀名
    let ext = path.extname(filePath).slice(1);
    // 获取对应的类型
    let type = mimes[ext];
    if(type) {//匹配到了
      if(ext === 'html') {
        response.setHeader("content-type", type+';charset=utf-8');
      }else {
        response.setHeader("content-type", type);
      }
      
    }else {//没匹配到
      response.setHeader("content-type", mimes.unknown);
    }
    
    response.end(data);
  });
});
// 3.监听端口，启动服务
server.listen(8080, () => {
  console.log("服务已经启动。。。端口8080监听中。。。。");
});
